#import "BaseUIViewController.h"
#import "RegisterViewController.h"
#import "LoginViewController.h"
#import "BaseNavigationController.h"
#import "CMActionSheet.h"

@implementation BaseUIViewController

@synthesize baseCommentField,baseCommentView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)dealloc {
    PP_RELEASE(baseHud);
    PP_RELEASE(baseTitle);
    PP_RELEASE(baseCommentView);
    PP_RELEASE(baseCommentField);
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    baseHud = [[MBProgressHUD alloc] initWithView:self.view];
    baseHud.mode = MBProgressHUDModeText;
    baseHud.removeFromSuperViewOnHide = YES;
    
    //demonstrate inner shadow
    baseTitle = [[FXLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 47)];
    baseTitle.font = [UIFont boldSystemFontOfSize:22.0f];
    baseTitle.backgroundColor = [UIColor clearColor];
    baseTitle.textAlignment = UITextAlignmentCenter;
    baseTitle.innerShadowColor = UIColorFromRGB(0x004da3, 0.8f);
    baseTitle.innerShadowOffset = CGSizeMake(0.0f, 1.0f);
    //demonstrate gradient fill
    baseTitle.gradientStartColor = UIColorFromRGB(0x008bcb, 1.0f);
    baseTitle.gradientEndColor = UIColorFromRGB(0x00b2f1, 1.0f);
    self.navigationItem.titleView = baseTitle;
    
    baseCommentOwner = nil;
}

- (void)viewDidUnload {
    PP_RELEASE(baseHud);
    PP_RELEASE(baseTitle);
    PP_RELEASE(baseCommentView);
    PP_RELEASE(baseCommentField);
    [super viewDidUnload];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)baseShowInfoHud:(NSString *)text andIsTop:(BOOL)isTop {
    if (isTop) {
        baseHud.yOffset = -100.0f;
    }
    baseHud.labelText = text;
    [self.view addSubview:baseHud];
    baseHud.opacity = PP_mbprogressHudOpacity;
    [baseHud show:YES];
    [baseHud hide:YES afterDelay:1.5];
}

//- (void)baseShowHUD:(NSString *)text atY:(float)y {
//    baseHud.yOffset = y;
//    baseHud.labelText = text;
//    [self.view addSubview:baseHud];
//    [baseHud show:YES];
//    [baseHud hide:YES afterDelay:1.5];
//}



#pragma mark -
#pragma mark -------登录弹出框----
//
//- (void)baseShowLoginSheet {
//    Log(@"mark");
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"你好像忘记登录了哟！"
//                                                             delegate:self
//                                                    cancelButtonTitle:@"取消"
//                                               destructiveButtonTitle:nil
//                                                    otherButtonTitles:@"注册", @"登录", nil];
//    [actionSheet showInView:self.view];
//    [actionSheet release];
//}



- (void)baseShowLoginSheet {
    CMActionSheet *actionSheet = [[[CMActionSheet alloc] init]autorelease];
    [actionSheet addButtonWithTitle:@"注册" type:CMActionSheetButtonTypeFreedom block:^{
        [self baseRegister];
    }];
    
    [actionSheet addSeparator];
    [actionSheet addButtonWithTitle:@"登录" type:CMActionSheetButtonTypeFreedom block:^{
        [self baseLogin];
        
    }];
    [actionSheet addSeparator];
    [actionSheet addButtonWithTitle:@"取消" type:CMActionSheetButtonTypeFreedom block:^{
        //
    }];
    [actionSheet present];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    switch (buttonIndex) {
        case 0: {
            Log(@"Register Selected");
            [self baseRegister];
            break;
        }
        case 1: {
            Log(@"Login Selected");
            [self baseLogin];
            break;
        }
    }
}

- (void)baseLogin {
    LoginViewController *login = [[[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil] autorelease];
    login.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    BaseNavigationController *loginNav = [[BaseNavigationController alloc]initWithRootViewController:login];
    [self.viewDeckController presentModalViewController:loginNav animated:YES];
}

- (void)baseRegister {
    RegisterViewController *regiseter = [[[RegisterViewController alloc]initWithNibName:@"RegisterViewController" bundle:nil] autorelease];
    regiseter.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    BaseNavigationController *regiseterNav = [[BaseNavigationController alloc]initWithRootViewController:regiseter];
    [self.viewDeckController presentModalViewController:regiseterNav animated:YES];
}

#pragma mark -
#pragma mark -------点击弹出评论框----

- (void)baseInitComment:(id<BaseUIViewControllerDelegate>)pCommentOwner btnName:(NSString *)btnStr{
    baseCommentOwner = pCommentOwner;
    
    baseCommentView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, 320, 40)];
    baseCommentView.backgroundColor = [UIColor redColor];
    baseCommentField = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(6, 3, 250, 40)];
    baseCommentField.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    baseCommentField.minNumberOfLines = 1;
    baseCommentField.maxNumberOfLines = 3;
    baseCommentField.returnKeyType = UIReturnKeyDone; //just as an example
    baseCommentField.font = [UIFont systemFontOfSize:15.0f];
    baseCommentField.delegate = self;
    baseCommentField.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    baseCommentField.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
#ifdef __IPHONE_5_0
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
#endif
    
    [self.view addSubview:baseCommentView];
    
    UIImage *rawEntryBackground = [UIImage imageNamed:@"comment_input.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[UIImageView alloc] initWithImage:entryBackground];
    entryImageView.frame = CGRectMake(5, 0, 251, 40);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"comment_Bg.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:background];
    imageView.frame = CGRectMake(0, 0, baseCommentView.frame.size.width, baseCommentView.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    baseCommentField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    // view hierachy
    [baseCommentView addSubview:imageView];
    [baseCommentView addSubview:baseCommentField];
    [baseCommentView addSubview:entryImageView];
    
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"comment_submit_1.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"comment_submit_2.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    doneBtn.frame = CGRectMake(baseCommentView.frame.size.width - 60, 0, 55, 40);
    doneBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    [doneBtn setTitle:btnStr forState:UIControlStateNormal];
    doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    
    [doneBtn setTitleColor:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0] forState:UIControlStateNormal];
    [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [doneBtn addTarget:self action:@selector(baseCommentBtn:) forControlEvents:UIControlEventTouchUpInside];
    [doneBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [doneBtn setBackgroundImage:selectedSendBtnBackground forState:UIControlStateHighlighted];
    [baseCommentView addSubview:doneBtn];
    baseCommentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
}

- (void)baseCommentBtn:(id)sender {
    [baseCommentOwner BVCcommentDone:self.baseCommentField];
}

- (void)baseShowComment {
    [baseCommentField becomeFirstResponder];
}

- (void)baseHideComment {
    [baseCommentField resignFirstResponder];
}

- (void)baseOnlyComment {
    self.baseCommentView.frame = CGRectMake(0, self.view.frame.size.height - self.baseCommentView.frame.size.height, 320, self.baseCommentView.frame.size.height);
    [baseCommentField resignFirstResponder];
}

- (void)keyboardWillShow:(NSNotification *)note {
    // get keyboard size and loctaion
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    // get a rect for the textView frame
    CGRect containerFrame = baseCommentView.frame;
    containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    baseCommentView.frame = containerFrame;
    
    // commit animations
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)note {
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // get a rect for the textView frame
    CGRect containerFrame = baseCommentView.frame;
    containerFrame.origin.y = self.view.bounds.size.height;
    
    // animations settings
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
    // set views with new info
    baseCommentView.frame = containerFrame;
    
    // commit animations
    [UIView commitAnimations];
    [baseCommentOwner BVCcommentHide:self.baseCommentView];
}

#pragma mark -
#pragma mark -------UITextFieldDelegate 协议方法-------

-(BOOL)growingTextViewShouldReturn:(HPGrowingTextView *)growingTextView {
	[growingTextView resignFirstResponder];
	return YES;
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    CGRect r = baseCommentView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
    baseCommentView.frame = r;
}

- (void)presentAppStoreForID:(NSNumber *)appStoreID inView:(UIView *)view withDelegate:(id<SKStoreProductViewControllerDelegate>)delegate withURL:(NSURL *)appStoreURL
{
    if(NSClassFromString(@"SKStoreProductViewController")) { // Checks for iOS 6 feature.
        SKStoreProductViewController *storeController = [[SKStoreProductViewController alloc] init];
        storeController.delegate = delegate; // productViewControllerDidFinish
        
        // Example app_store_id (e.g. for Words With Friends)
        // [NSNumber numberWithInt:322852954];
        
        NSDictionary *productParameters = @{ SKStoreProductParameterITunesItemIdentifier : appStoreID};
        
        [storeController loadProductWithParameters:productParameters completionBlock:^(BOOL result, NSError *error) {
            if (result) {
                [self presentModalViewController:storeController animated:YES];
            } else {
                [[[UIAlertView alloc] initWithTitle:@"Uh oh!" message:@"There was a problem displaying the game" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
            }
        }];
    } else { // Before iOS 6, we can only open the URL
        [[UIApplication sharedApplication] openURL:appStoreURL];
    }
}

- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController {
    [viewController dismissModalViewControllerAnimated:YES];
}

@end
